package com.dz.web.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dz.common.context.FacadeContext;
import com.dz.common.context.UserContextVO;
import com.dz.utils.redis.RedisUtil;

@Slf4j
public class ContextInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private RedisUtil redisUtil;

	@Autowired(required = false)
	private SessionService sessionService;

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		UserContextVO userContextVO = FacadeContext.getCurrentUser();
		if (userContextVO == null) {
			String token = request.getHeader("token");
			if (sessionService != null && token != null) {
				try {
					JSONObject userInfo = sessionService.getSessionInfo(token);
					if (userInfo != null) {
						userContextVO = new UserContextVO();
						userContextVO.setOpenId(userInfo.getString("openId"));
						if (userInfo.containsKey("id")) {
							userContextVO.setCustId(userInfo.getLong("id"));
						}
						FacadeContext.setUser(userContextVO);
						log.info("set context success:"+JSON.toJSONString(userContextVO));
					}
				} catch (Exception ex) {
					log.error("get session error:"+ex.getMessage(),ex);
				}
			} else {
				log.warn("not found token by reqeust:{}", request.getRequestURI());
			}
		}
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
		FacadeContext.remove();
	}
}
